/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.zxing.journeyapps.barcodescanner;

import java.util.Map;
import java.util.WeakHashMap;
import java.util.logging.Logger;

public class BusHelper {
    private static final String TAG = "BusHelper";
    private static volatile  BusHelper INSTANCE;
    private Map<String, Observable> callbacks;

    public interface Observable {
        void onSubscribe(Object object);
    }

    private BusHelper() {
        callbacks = new WeakHashMap<>();
    }

    public static BusHelper getINSTANCE() {
        if (INSTANCE == null) {
            synchronized (BusHelper.class) {
                if (INSTANCE == null) {
                    INSTANCE = new BusHelper();
                }
            }
        }
        return INSTANCE;
    }

    public boolean register(String action,Observable observable) {
        if (action == null || action.trim().isEmpty()) {
            return false;
        }
        if (observable == null) {
            return false;
        }
        if (callbacks.containsKey(action)) {
            Logger.getLogger(TAG).warning(String.format("the callbacks contains action[%s], now will replace old observable to new observable in the same key position!",action));
        }
        callbacks.put(action, observable);
        return true;
    }

    public boolean unRegister(Observable observable) {
        if (observable == null) {
            return false;
        }
        if (callbacks.containsValue(observable)) {
            callbacks.remove(observable);
            return true;
        }
        return false;
    }

    public boolean sendAction(String action, Object o) {
        if (action == null || action.trim().isEmpty()) {
            return false;
        }
        if (callbacks.containsKey(action)) {
            Observable observable = callbacks.get(action);
            if (observable != null) {
                observable.onSubscribe(o);
                return true;
            }
        }
        return false;
    }
}
